package com.example.imserver.repository;

import com.example.imserver.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
    // 获取两个用户之间的消息
    @Query("SELECT m FROM Message m WHERE " +
           "((m.senderId = :userId1 AND m.receiverId = :userId2) OR " +
           "(m.senderId = :userId2 AND m.receiverId = :userId1)) " +
           "AND m.isDeleted = false " +
           "ORDER BY m.createdAt ASC")
    List<Message> findConversation(@Param("userId1") Long userId1, @Param("userId2") Long userId2);
    
    // 获取用户的未读消息
    @Query("SELECT m FROM Message m WHERE m.receiverId = :userId AND m.isRead = false AND m.isDeleted = false")
    List<Message> findUnreadMessages(@Param("userId") Long userId);
    
    // 获取最近聊天列表（最后一条消息）
    @Query("SELECT m FROM Message m WHERE " +
           "(m.senderId = :userId OR m.receiverId = :userId) " +
           "AND m.isDeleted = false " +
           "AND m.id IN (SELECT MAX(m2.id) FROM Message m2 WHERE " +
           "(m2.senderId = :userId OR m2.receiverId = :userId) " +
           "AND m2.isDeleted = false " +
           "GROUP BY CASE WHEN m2.senderId = :userId THEN m2.receiverId ELSE m2.senderId END)")
    List<Message> findRecentChats(@Param("userId") Long userId);
}

